package com.juzipi.demo.utils;

import org.quartz.*;

import java.util.Map;

public class QuartzUtils {


    //创建
    public static void createJob(Scheduler scheduler, Class<? extends Job> jobClass, String jobName, String jobGroup, String cron, Map<String,Object> param) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroup).build();
        if (StringUtils.isNotEmpty(param)){
            param.forEach((k,v)-> jobDetail.getJobDataMap().put(k,v));
        }
        scheduler.scheduleJob(jobDetail,buildCronTrigger(jobName,jobGroup,cron));
    }

    //构建trigger
    private static Trigger buildCronTrigger(String jobName,String jobGroup,String cron){
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        return TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup).withSchedule(cronScheduleBuilder).build();
    }


    //刷新
    public static void refreshJob(Scheduler scheduler,String jobName,String jobGroup,String cron) throws SchedulerException {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
        scheduler.rescheduleJob(triggerKey,buildCronTrigger(jobName, jobGroup, cron));
    }

    //恢复
    public static void resumeJob(Scheduler scheduler,String jobName,String jobGroup) throws SchedulerException {
        scheduler.resumeJob(JobKey.jobKey(jobName,jobGroup));
    }

    //暂停
    public static void pauseJob(Scheduler scheduler,String jobName,String jobGroup) throws SchedulerException {
        scheduler.pauseJob(JobKey.jobKey(jobName,jobGroup));
    }

    public static void deleteJob(Scheduler scheduler,String jobName,String jobGroup) throws SchedulerException {
        scheduler.unscheduleJob(TriggerKey.triggerKey(jobName,jobGroup));
        scheduler.deleteJob(JobKey.jobKey(jobName,jobGroup));
    }
}
